<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Admin\BaseController;
use App\Models\Admin\User;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    public function toCreate()
    {
        $user = new User();
        return view('admin.auth.user.user',compact('user'));
    }
    public function toEdit(User $user)
    {
        if($user->id == 1){
            return redirect()->back()->with('error','超级管理员不允许编辑');
        }
        return view('admin.auth.user.user', compact('user'));
    }

    public function save(Request $request)
    {
        if($request->input('id')){
            if($request->input('id') == 1){
                return redirect()->back()->with('error','超级管理员不允许编辑');
            }
            $user = User::find($request->input('id'));
            $user->name = $request->input('name');
            $user->phone = $request->input('phone');
            $user->email = $request->input('phone');
            if($request->input('password')){
                $user->password = bcrypt($request->input('password'));
            }
        }else{
            $cnt1 = User::where('name', $request->input('name'))->count();
            $cnt2 = User::where('phone', $request->input('phone'))->count();
            if($cnt1 && $cnt2){
                return $this->error('用户名和手机号已被注册');
            }else if($cnt1){
                return $this->error('用户名已被注册');
            }else if($cnt2){
                return $this->error('手机号已被注册');
            }
            $user = new User();
            $user->name = $request->input('name');
            $user->phone = $request->input('phone');
            $user->email = $request->input('phone');
            $user->password = bcrypt($request->input('password'));
        }
        $ret = $user->save();

        if($ret){
            return $this->success('提交成功', route('admin-users'));
        }else{
            return $this->error('提交失败');
        }
    }

    public function users()
    {
        $users = User::all();//where('status', 1)->get();
        return view('admin.auth.user.users', compact('users'));
    }

    public function attachRole(Request $request)
    {
        $user_id = $request->input('user_id');
        if($user_id == 1){
            return redirect()->back()->with('error','超级管理员不允许编辑');
        }
        $ids = $request->input('ids');
        $user = User::find($user_id);
        $ret = $user->roles()->sync(explode(',', $ids));
        if($ret){
            return $this->success('提交成功');
        }else{
            return $this->error();
        }
    }

    public function delete(User $user){
        $user->status = 0;
        $ret = $user->save();
        if($ret){
            return $this->success('删除成功');
        }else{
            return $this->error();
        }
    }
}
